import $V from './$V';
import ma from './ma';
import ema from './ema';

export default function boll(data, length, width, type) {
  let middle = $V.init(data.length, 0);
  let upper = $V.init(data.length, 0);
  let low = $V.init(data.length, 0);
  if (type === 'ma') {
    middle = ma(data, length);
    upper = $V.copy_by_range(upper, $V.range(length), $V.subv(middle, 0, length));
    low = $V.copy_by_range(low, $V.range(length), $V.subv(middle, 0, length));
    for (let i = length; i < data.length; i++) {
      upper[i] = middle[i] + width * $V.std($V.subv(data, i - length, i));
      low[i] = middle[i] - width * $V.std($V.subv(data, i - length, i));
    }
  } else {
    middle = ema(data, length);
    upper = $V.copy_by_range(upper, $V.range(length), $V.subv(middle, 0, length));
    low = $V.copy_by_range(low, $V.range(length), $V.subv(middle, 0, length));
    for (let i = length; i < data.length; i++) {
      const standev = Math.sqrt($V.sum($V.div_constant($V.square($V.sub_constant($V.subv(data, i - length, i), middle[i])), length)));
      upper[i] = middle[i] + width * standev;
      low[i] = middle[i] - width * standev;
    }
  }
  return { middle, upper, low };
}
